package gl.web.apk.controller;

import gl.web.apk.common.config.Config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

import com.jfinal.core.Controller;
import com.jfinal.log.Log;
import com.jfinal.upload.UploadFile;

public class UploadController extends Controller {
	private Log log = Log.getLog(UploadController.class);

	public void index() {
		redirect("/upload/file");
		renderText("post /upload/file to upload a file ");
	}

	public void file() {
		try {

			UploadFile uploadFile = this.getFile();
			
			log.info("upload a file,the uploadFile is:" + uploadFile);
			String fileName = uploadFile.getOriginalFileName();

			File file = uploadFile.getFile();
			log.info("upload a file,the file name is:" + fileName);

			File t = new File(Config.getImgDir() + fileName);
			try {
				t.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
			fileChannelCopy(file, t);
			log.info("copy a file to :" + t.getAbsolutePath() + " from"
					+ file.getAbsolutePath());
			file.delete();
			this.renderText(t.getName());
		} catch (Exception e) {
			e.printStackTrace();
			this.renderText(e.getMessage());
		}
	}
	/**
	 * 上传到doc目录
	 */
	public void doc() {
		try {

			UploadFile uploadFile = this.getFile();
			
			String fileName = uploadFile.getOriginalFileName();

			File file = uploadFile.getFile();

			File t = new File(Config.getWebRootPath() +"/doc/"+ fileName);
			try {
				t.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
			fileChannelCopy(file, t);
			log.info("copy a file to :" + t.getAbsolutePath() + " from"
					+ file.getAbsolutePath());
			file.delete();
			this.renderText(t.getName());
		} catch (Exception e) {
			e.printStackTrace();
			this.renderText(e.getMessage());
		}
	}
	public void fileChannelCopy(File s, File t) {
		FileInputStream fi = null;
		FileOutputStream fo = null;
		FileChannel in = null;
		FileChannel out = null;
		try {
			fi = new FileInputStream(s);
			fo = new FileOutputStream(t);
			in = fi.getChannel();// 得到对应的文件通道
			out = fo.getChannel();// 得到对应的文件通道
			in.transferTo(0, in.size(), out);// 连接两个通道，并且从in通道读取，然后写入out通道
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fi.close();
				in.close();
				fo.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
